package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClientUtil fastDFSClientUtil;

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        WmMaterial wmMaterial = new WmMaterial();

        try {
            //1.检查参数
            if(multipartFile == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            String filepath = fastDFSClientUtil.uploadFile(multipartFile);
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setUrl(filepath);
            WmUser user = WmThreadLocalUtils.getUser();
            if (user!=null){
                wmMaterial.setUserId(user.getId());
            }
            save(wmMaterial);
            //拼接图片路径
            wmMaterial.setUrl(fileServerUrl+filepath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //按照日期倒序排序
        LambdaQueryWrapper<WmMaterial> queryWrapper=new LambdaQueryWrapper<>();
        if (dto.getIsCollection()==1){
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page pageParam = new Page(dto.getPage(),dto.getSize());
        IPage resultPage = page(pageParam, queryWrapper);
        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)resultPage.getTotal());
        List<WmMaterial> list = resultPage.getRecords();
        list=list.stream().map(a->{
            a.setUrl(fileServerUrl.concat(a.getUrl()));
            return a;
        }).collect(Collectors.toList());
        responseResult.setData(list);
        return responseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        WmMaterial wmMaterial=getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        QueryWrapper<WmNewsMaterial> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("material_id",id);
        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //删除逻辑 删图片fastdfs
        fastDFSClientUtil.delFile(wmMaterial.getUrl());
        boolean remove = removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        Integer uid = WmThreadLocalUtils.getUser().getId();

        if (id != null && uid != null) {
            //2.更新状态
            //获取当前用户信息
            update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, type)
                    .eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, uid));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
